// 主页面逻辑
let currentUser = null;
let currentUserType = null;

// 页面加载时检查登录状态
window.onload = function() {
    checkLoginStatus();
    initializePage();
};

// 检查登录状态
function checkLoginStatus() {
    const user = localStorage.getItem('currentUser');
    const userType = localStorage.getItem('currentUserType');
    
    if (user && userType) {
        currentUser = JSON.parse(user);
        currentUserType = userType;
        showUserContent();
    } else {
        showLoginPrompt();
    }
}

// 显示用户内容
function showUserContent() {
    document.getElementById('login-prompt').style.display = 'none';
    document.getElementById('user-content').style.display = 'block';
    
    // 显示用户信息
    document.getElementById('user-info').innerHTML = `
        <h2>欢迎，${currentUser.username}！</h2>
        <p>用户类型：${getUserTypeText(currentUserType)}</p>
        <button onclick="logout()" class="logout-btn">退出登录</button>
    `;
    
    // 根据用户类型显示相应的导航
    showNavigationForUserType();
    
    // 默认显示用户对应的主页面
    showDefaultSection();
}

// 显示登录提示
function showLoginPrompt() {
    document.getElementById('login-prompt').style.display = 'block';
    document.getElementById('user-content').style.display = 'none';
}

// 根据用户类型显示导航
function showNavigationForUserType() {
    const nav = document.getElementById('navigation');
    nav.innerHTML = '';
    
    if (currentUserType === 'user') {
        nav.innerHTML = `
            <button onclick="showSection('user-home')" class="nav-btn">用户首页</button>
            <button onclick="showSection('user-orders')" class="nav-btn">我的订单</button>
            <button onclick="showSection('user-profile')" class="nav-btn">个人资料</button>
        `;
    } else if (currentUserType === 'merchant') {
        nav.innerHTML = `
            <button onclick="showSection('merchant-home')" class="nav-btn">商家首页</button>
            <button onclick="showSection('merchant-dishes')" class="nav-btn">菜品管理</button>
            <button onclick="showSection('merchant-orders')" class="nav-btn">订单管理</button>
            <button onclick="showSection('merchant-stats')" class="nav-btn">数据统计</button>
        `;
    } else if (currentUserType === 'rider') {
        nav.innerHTML = `
            <button onclick="showSection('rider-home')" class="nav-btn">骑手首页</button>
            <button onclick="showSection('rider-orders')" class="nav-btn">接单管理</button>
            <button onclick="showSection('rider-map')" class="nav-btn">地图导航</button>
            <button onclick="showSection('rider-profile')" class="nav-btn">个人资料</button>
        `;
    }
}

// 显示默认页面
function showDefaultSection() {
    if (currentUserType === 'user') {
        showSection('user-home');
    } else if (currentUserType === 'merchant') {
        showSection('merchant-home');
    } else if (currentUserType === 'rider') {
        showSection('rider-home');
    }
}

// 显示指定页面
function showSection(sectionName) {
    // 隐藏所有页面
    const sections = document.querySelectorAll('.content-section');
    sections.forEach(section => {
        section.style.display = 'none';
    });
    
    // 显示指定页面
    const targetSection = document.getElementById(sectionName);
    if (targetSection) {
        targetSection.style.display = 'block';
        loadSectionContent(sectionName);
    }
}

// 加载页面内容
function loadSectionContent(sectionName) {
    switch(sectionName) {
        case 'user-home':
            loadUserHome();
            break;
        case 'user-orders':
            loadUserOrders();
            break;
        case 'user-profile':
            loadUserProfile();
            break;
        case 'merchant-home':
            loadMerchantHome();
            break;
        case 'merchant-dishes':
            loadMerchantDishes();
            break;
        case 'merchant-orders':
            loadMerchantOrders();
            break;
        case 'merchant-stats':
            loadMerchantStats();
            break;
        case 'rider-home':
            loadRiderHome();
            break;
        case 'rider-orders':
            loadRiderOrders();
            break;
        case 'rider-map':
            loadRiderMap();
            break;
        case 'rider-profile':
            loadRiderProfile();
            break;
    }
}

// 用户首页
function loadUserHome() {
    const content = document.getElementById('user-home');
    content.innerHTML = `
        <div class="section-header">
            <h2>用户首页</h2>
            <p>欢迎使用外卖平台，开始您的美食之旅！</p>
        </div>
        <div class="feature-grid">
            <div class="feature-card">
                <div class="feature-icon">🍽️</div>
                <h3>浏览美食</h3>
                <p>发现附近的美食餐厅，享受各种美味佳肴</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon">📱</div>
                <h3>快速下单</h3>
                <p>简单几步即可完成下单，享受便捷的外卖服务</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon">🚚</div>
                <h3>实时配送</h3>
                <p>实时跟踪订单状态，了解配送进度</p>
            </div>
            <div class="feature-card">
                <div class="feature-icon">⭐</div>
                <h3>评价反馈</h3>
                <p>为您的用餐体验打分，帮助其他用户选择</p>
            </div>
        </div>
    `;
}

// 用户订单
function loadUserOrders() {
    const content = document.getElementById('user-orders');
    content.innerHTML = `
        <div class="section-header">
            <h2>我的订单</h2>
            <p>查看您的订单历史和当前订单状态</p>
                    </div>
        <div class="orders-list">
            <div class="order-card">
                <div class="order-header">
                    <span class="order-id">订单号: #12345</span>
                    <span class="order-status completed">已完成</span>
                </div>
                <div class="order-content">
                    <p>餐厅：美味餐厅</p>
                    <p>菜品：宫保鸡丁 x1, 米饭 x1</p>
                    <p>总价：¥28.00</p>
                    <p>下单时间：2024-01-15 12:30</p>
            </div>
            </div>
            <div class="order-card">
                <div class="order-header">
                    <span class="order-id">订单号: #12346</span>
                    <span class="order-status delivering">配送中</span>
                        </div>
                <div class="order-content">
                    <p>餐厅：川菜馆</p>
                    <p>菜品：麻婆豆腐 x1, 米饭 x1</p>
                    <p>总价：¥22.00</p>
                    <p>下单时间：2024-01-15 18:45</p>
                        </div>
                    </div>
            </div>
        `;
}

// 用户资料
function loadUserProfile() {
    const content = document.getElementById('user-profile');
    content.innerHTML = `
        <div class="section-header">
            <h2>个人资料</h2>
            <p>管理您的个人信息和账户设置</p>
        </div>
        <div class="profile-form">
            <div class="form-group">
                <label>用户名：</label>
                <input type="text" value="${currentUser.username}" readonly>
            </div>
            <div class="form-group">
                <label>手机号：</label>
                <input type="text" value="${currentUser.phone || '未设置'}" readonly>
            </div>
            <div class="form-group">
                <label>邮箱：</label>
                <input type="email" value="${currentUser.email || '未设置'}" readonly>
            </div>
            <div class="form-group">
                <label>注册时间：</label>
                <input type="text" value="${currentUser.registerTime || '未知'}" readonly>
            </div>
        </div>
    `;
}

// 商家首页
function loadMerchantHome() {
    const content = document.getElementById('merchant-home');
    content.innerHTML = `
        <div class="section-header">
            <h2>商家首页</h2>
            <p>管理您的餐厅，提升经营效率</p>
        </div>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">📊</div>
                <h3>今日订单</h3>
                <p class="stat-number">24</p>
                <p class="stat-change">+12%</p>
            </div>
            <div class="stat-card">
                <div class="stat-icon">💰</div>
                <h3>今日收入</h3>
                <p class="stat-number">¥1,280</p>
                <p class="stat-change">+8%</p>
            </div>
            <div class="stat-card">
                <div class="stat-icon">⭐</div>
                <h3>平均评分</h3>
                <p class="stat-number">4.6</p>
                <p class="stat-change">+0.2</p>
            </div>
            <div class="stat-card">
                <div class="stat-icon">🍽️</div>
                <h3>菜品数量</h3>
                <p class="stat-number">15</p>
                <p class="stat-change">+2</p>
            </div>
        </div>
        <div class="quick-actions">
            <button onclick="showSection('merchant-dishes')" class="action-btn">
                <span class="btn-icon">🍽️</span>
                菜品管理
            </button>
            <button onclick="showSection('merchant-orders')" class="action-btn">
                <span class="btn-icon">📋</span>
                订单管理
            </button>
            <button onclick="openDishUpload()" class="action-btn">
                <span class="btn-icon">➕</span>
                添加菜品
            </button>
        </div>
    `;
}

// 商家菜品管理
function loadMerchantDishes() {
    const content = document.getElementById('merchant-dishes');
    content.innerHTML = `
        <div class="section-header">
            <h2>菜品管理</h2>
            <p>管理您的菜品信息，提升菜品展示效果</p>
            <button onclick="openDishUpload()" class="add-dish-btn">+ 添加新菜品</button>
        </div>
        <div class="dishes-grid" id="dishes-grid">
            <!-- 菜品将通过JavaScript动态加载 -->
        </div>
    `;
    
    // 加载菜品数据
    loadDishesData();
}

// 加载菜品数据
async function loadDishesData() {
    const res = await fetch('http://localhost:8080/api/dishes?merchantId=2');
    const dishes = await res.json();
    const grid = document.getElementById('dishes-grid');
    
    if (dishes.length === 0) {
        grid.innerHTML = `
            <div class="no-dishes">
                <p>暂无菜品，点击"添加新菜品"开始添加</p>
            </div>
        `;
        return;
    }
    
    grid.innerHTML = dishes.map(dish => `
        <div class="dish-card">
            <div class="dish-image">
                <img src="${dish.image || 'https://via.placeholder.com/200x150?text=菜品图片'}" alt="${dish.name}">
            </div>
            <div class="dish-info">
                <h3>${dish.name}</h3>
                <p class="dish-price">¥${dish.price}</p>
                <p class="dish-category">${dish.category}</p>
                <p class="dish-description">${dish.description}</p>
                <div class="dish-actions">
                    <button onclick="editDish(${dish.id})" class="edit-btn">编辑</button>
                    <button onclick="deleteDish(${dish.id})" class="delete-btn">删除</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 商家订单管理
function loadMerchantOrders() {
    const content = document.getElementById('merchant-orders');
    content.innerHTML = `
        <div class="section-header">
            <h2>订单管理</h2>
            <p>处理订单，管理配送状态</p>
        </div>
        <div class="orders-tabs">
            <button class="tab-btn active" onclick="showOrderTab('pending')">待处理</button>
            <button class="tab-btn" onclick="showOrderTab('preparing')">制作中</button>
            <button class="tab-btn" onclick="showOrderTab('ready')">待配送</button>
            <button class="tab-btn" onclick="showOrderTab('completed')">已完成</button>
        </div>
        <div class="orders-list" id="orders-list">
            <!-- 订单列表将通过JavaScript动态加载 -->
        </div>
    `;
    
    showOrderTab('pending');
}

// 显示订单标签页
function showOrderTab(status) {
    // 更新标签页状态
    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    // 加载对应状态的订单
    loadOrdersByStatus(status);
}

// 根据状态加载订单
async function loadOrdersByStatus(status) {
    const res = await fetch('http://localhost:8080/api/orders?merchantId=2&status=' + encodeURIComponent(status));
    const filteredOrders = await res.json();
    const ordersList = document.getElementById('orders-list');
    
    if (filteredOrders.length === 0) {
        ordersList.innerHTML = `
            <div class="no-orders">
                <p>暂无${getStatusText(status)}订单</p>
            </div>
        `;
        return;
    }
    
    ordersList.innerHTML = filteredOrders.map(order => `
        <div class="order-card">
            <div class="order-header">
                <span class="order-id">订单号: #${order.id}</span>
                <span class="order-status ${order.status}">${getStatusText(order.status)}</span>
            </div>
            <div class="order-content">
                <p>客户：${order.customerName}</p>
                <p>菜品：${order.dishes.map(dish => `${dish.name} x${dish.quantity}`).join(', ')}</p>
                <p>总价：¥${order.totalPrice}</p>
                <p>下单时间：${order.orderTime}</p>
            </div>
            <div class="order-actions">
                ${getOrderActions(order.status, order.id)}
            </div>
        </div>
    `).join('');
}

// 获取订单操作按钮
function getOrderActions(status, orderId) {
    switch(status) {
        case 'pending':
            return `<button onclick="updateOrderStatus(${orderId}, 'preparing')" class="action-btn">开始制作</button>`;
        case 'preparing':
            return `<button onclick="updateOrderStatus(${orderId}, 'ready')" class="action-btn">制作完成</button>`;
        case 'ready':
            return `<button onclick="updateOrderStatus(${orderId}, 'completed')" class="action-btn">订单完成</button>`;
        default:
            return '';
    }
}

// 更新订单状态
async function updateOrderStatus(orderId, newStatus) {
    await fetch('http://localhost:8080/api/orders/' + orderId, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: newStatus })
    });
    loadOrdersByStatus(newStatus);
}

// 商家数据统计
function loadMerchantStats() {
    const content = document.getElementById('merchant-stats');
    content.innerHTML = `
        <div class="section-header">
            <h2>数据统计</h2>
            <p>分析您的经营数据，优化经营策略</p>
        </div>
        <div class="stats-overview">
            <div class="chart-container">
                <h3>销售趋势</h3>
                <div class="chart-placeholder">
                    <p>📈 销售趋势图表</p>
                    <p>（这里可以集成图表库显示实际数据）</p>
                </div>
            </div>
            <div class="chart-container">
                <h3>热门菜品</h3>
                <div class="chart-placeholder">
                    <p>🍽️ 热门菜品排行</p>
                    <p>（这里可以显示菜品销量排行）</p>
                </div>
            </div>
        </div>
    `;
}

// 骑手首页
function loadRiderHome() {
    const content = document.getElementById('rider-home');
    content.innerHTML = `
        <div class="section-header">
            <h2>骑手首页</h2>
            <p>管理您的配送任务，提升配送效率</p>
        </div>
        <div class="rider-stats">
            <div class="stat-card">
                <div class="stat-icon">📦</div>
                <h3>今日配送</h3>
                <p class="stat-number">18</p>
                <p class="stat-change">+3</p>
            </div>
            <div class="stat-card">
                <div class="stat-icon">💰</div>
                <h3>今日收入</h3>
                <p class="stat-number">¥156</p>
                <p class="stat-change">+¥24</p>
            </div>
            <div class="stat-card">
                <div class="stat-icon">⭐</div>
                <h3>服务评分</h3>
                <p class="stat-number">4.8</p>
                <p class="stat-change">+0.1</p>
            </div>
            <div class="stat-card">
                <div class="stat-icon">⏱️</div>
                <h3>平均用时</h3>
                <p class="stat-number">25分钟</p>
                <p class="stat-change">-2分钟</p>
            </div>
        </div>
        <div class="quick-actions">
            <button onclick="showSection('rider-orders')" class="action-btn">
                <span class="btn-icon">📋</span>
                接单管理
            </button>
            <button onclick="showSection('rider-map')" class="action-btn">
                <span class="btn-icon">🗺️</span>
                地图导航
            </button>
        </div>
    `;
}

// 骑手订单管理
function loadRiderOrders() {
    const content = document.getElementById('rider-orders');
    content.innerHTML = `
        <div class="section-header">
            <h2>接单管理</h2>
            <p>查看可接订单，管理配送任务</p>
        </div>
        <div class="orders-tabs">
            <button class="tab-btn active" onclick="showRiderOrderTab('available')">可接订单</button>
            <button class="tab-btn" onclick="showRiderOrderTab('accepted')">已接订单</button>
            <button class="tab-btn" onclick="showRiderOrderTab('delivering')">配送中</button>
            <button class="tab-btn" onclick="showRiderOrderTab('completed')">已完成</button>
        </div>
        <div class="orders-list" id="rider-orders-list">
            <!-- 骑手订单列表将通过JavaScript动态加载 -->
        </div>
    `;
    
    showRiderOrderTab('available');
}

// 显示骑手订单标签页
function showRiderOrderTab(status) {
    // 更新标签页状态
    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    // 加载对应状态的订单
    loadRiderOrdersByStatus(status);
}

// 根据状态加载骑手订单
async function loadRiderOrdersByStatus(status) {
    const res = await fetch('http://localhost:8080/api/orders?riderStatus=' + encodeURIComponent(status));
    const filteredOrders = await res.json();
    const ordersList = document.getElementById('rider-orders-list');
    
    if (filteredOrders.length === 0) {
        ordersList.innerHTML = `
            <div class="no-orders">
                <p>暂无${getRiderStatusText(status)}订单</p>
            </div>
        `;
        return;
    }
    
    ordersList.innerHTML = filteredOrders.map(order => `
        <div class="order-card">
            <div class="order-header">
                <span class="order-id">订单号: #${order.id}</span>
                <span class="order-status ${order.riderStatus}">${getRiderStatusText(order.riderStatus)}</span>
            </div>
            <div class="order-content">
                <p>餐厅：${order.restaurantName}</p>
                <p>客户：${order.customerName}</p>
                <p>配送地址：${order.deliveryAddress}</p>
                <p>配送费：¥${order.deliveryFee}</p>
                <p>预计用时：${order.estimatedTime}分钟</p>
            </div>
            <div class="order-actions">
                ${getRiderOrderActions(order.riderStatus, order.id)}
            </div>
        </div>
    `).join('');
}

// 获取骑手订单操作按钮
function getRiderOrderActions(status, orderId) {
    switch(status) {
        case 'available':
            return `<button onclick="acceptOrder(${orderId})" class="action-btn">接单</button>`;
        case 'accepted':
            return `<button onclick="startDelivery(${orderId})" class="action-btn">开始配送</button>`;
        case 'delivering':
            return `<button onclick="completeDelivery(${orderId})" class="action-btn">完成配送</button>`;
        default:
            return '';
    }
}

// 接单
async function acceptOrder(orderId) {
    await fetch('http://localhost:8080/api/orders/' + orderId, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ riderStatus: 'accepted' }) });
    loadRiderOrdersByStatus('accepted');
}

// 开始配送
async function startDelivery(orderId) {
    await fetch('http://localhost:8080/api/orders/' + orderId, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ riderStatus: 'delivering' }) });
    loadRiderOrdersByStatus('delivering');
}

// 完成配送
async function completeDelivery(orderId) {
    await fetch('http://localhost:8080/api/orders/' + orderId, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ riderStatus: 'completed' }) });
    loadRiderOrdersByStatus('completed');
}

// 骑手地图
function loadRiderMap() {
    const content = document.getElementById('rider-map');
    content.innerHTML = `
        <div class="section-header">
            <h2>地图导航</h2>
            <p>查看配送路线，优化配送路径</p>
            </div>
        <div class="map-container">
            <div id="rider-map" class="map-placeholder">
                <div class="map-content">
                    <h3>🗺️ 配送地图</h3>
                    <p>当前位置：北京市朝阳区</p>
                    <p>待配送订单：3个</p>
                    <p>预计总用时：45分钟</p>
                    <div class="map-actions">
                        <button onclick="refreshMap()" class="action-btn">刷新地图</button>
                        <button onclick="showRoute()" class="action-btn">显示路线</button>
            </div>
            </div>
            </div>
            </div>
        `;
    
    // 初始化地图（这里可以集成真实的地图API）
    initializeRiderMap();
}

// 初始化骑手地图
function initializeRiderMap() {
    // 这里可以集成百度地图或其他地图API
    console.log('初始化骑手地图');
}

// 刷新地图
function refreshMap() {
    alert('地图已刷新');
}

// 显示路线
function showRoute() {
    alert('显示最优配送路线');
}

// 骑手资料
function loadRiderProfile() {
    const content = document.getElementById('rider-profile');
    content.innerHTML = `
        <div class="section-header">
            <h2>个人资料</h2>
            <p>管理您的个人信息和配送设置</p>
        </div>
        <div class="profile-form">
            <div class="form-group">
                <label>用户名：</label>
                <input type="text" value="${currentUser.username}" readonly>
            </div>
            <div class="form-group">
                <label>手机号：</label>
                <input type="text" value="${currentUser.phone || '未设置'}" readonly>
            </div>
            <div class="form-group">
                <label>配送区域：</label>
                <input type="text" value="朝阳区" readonly>
            </div>
            <div class="form-group">
                <label>配送工具：</label>
                <input type="text" value="电动车" readonly>
            </div>
        </div>
    `;
}

// 打开菜品上传页面
function openDishUpload() {
    window.open('dish-upload.html', '_blank');
}

// 编辑菜品
function editDish(dishId) {
    // 这里可以打开编辑页面或弹窗
    alert(`编辑菜品 #${dishId}`);
}

// 删除菜品
function deleteDish(dishId) {
    if (confirm('确定要删除这个菜品吗？')) {
        // 这里应该调用后端API删除菜品
        alert(`菜品 #${dishId} 已删除`);
        loadDishesData();
    }
}

// 退出登录
function logout() {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('currentUserType');
    currentUser = null;
    currentUserType = null;
    showLoginPrompt();
}

// 初始化页面
function initializePage() {
    // 检查URL hash，如果有的话显示对应页面
    const hash = window.location.hash.substring(1);
    if (hash && currentUser) {
        showSection(hash);
    }
}

// 工具函数
function getUserTypeText(userType) {
    const types = {
        'user': '普通用户',
        'merchant': '商家',
        'rider': '骑手'
    };
    return types[userType] || '未知';
}

function getStatusText(status) {
    const statuses = {
        'pending': '待处理',
        'preparing': '制作中',
        'ready': '待配送',
        'completed': '已完成'
    };
    return statuses[status] || status;
}

function getRiderStatusText(status) {
    const statuses = {
        'available': '可接单',
        'accepted': '已接单',
        'delivering': '配送中',
        'completed': '已完成'
    };
    return statuses[status] || status;
}

// 数据库相关函数（模拟）
function getDishesFromDatabase() { return []; }

function getOrdersFromDatabase() { return []; }
